package net.pws.common.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class HashUtils {

	private static final Log logger = LogFactory.getLog(HashUtils.class);

	public final static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	/**
	 * 得到指定类型的Hash值
	 * 
	 * @param fileName
	 * @param hashType
	 *            支持的类型有 MD5 SHA1 SHA-256 SHA-384 SHA-512
	 * @return
	 * @throws Exception
	 */
	public static String getHash(String fileName, String hashType)
			throws Exception {
		InputStream fis;
		fis = new FileInputStream(fileName);
		String hash = getHash(fis, hashType);
		try {
			fis.close();
		} catch (Exception e) {
			logger.error(e, e);
		}
		return hash;
	}

	public static String getHash(InputStream is, String hashType)
			throws Exception {
		byte[] buffer = new byte[1024];
		MessageDigest md5 = MessageDigest.getInstance(hashType);
		int numRead = 0;
		while ((numRead = is.read(buffer)) > 0) {
			md5.update(buffer, 0, numRead);
		}
		return toHexString(md5.digest());
	}

	public static String getHash(byte[] bytes, String hashType)
			throws Exception {
		MessageDigest md5 = MessageDigest.getInstance(hashType);
		md5.update(bytes);
		return toHexString(md5.digest());
	}

	public static String toHexString(byte[] b) {
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
			sb.append(hexChar[b[i] & 0x0f]);
		}
		return sb.toString();
	}
}